package com.shqcjd.sinopecdemomobile.ui.activity;

import android.content.Intent;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.amap.api.location.AMapLocation;
import com.amap.api.maps.AMapUtils;
import com.amap.api.maps.model.LatLng;
import com.shqcjd.sinopecdemomobile.R;
import com.shqcjd.sinopecdemomobile.api.ApiService;
import com.shqcjd.sinopecdemomobile.app.MyApp;
import com.shqcjd.sinopecdemomobile.helper.rxjavahelper.RxObserver;
import com.shqcjd.sinopecdemomobile.helper.rxjavahelper.RxSchedulersHelper;
import com.shqcjd.sinopecdemomobile.model.ResponseData;
import com.shqcjd.sinopecdemomobile.model.pojo.EquipmentGroupBean;
import com.shqcjd.sinopecdemomobile.model.pojo.IntentEquipmentBean;
import com.shqcjd.sinopecdemomobile.ui.activity.problem.ProblemFeedbackActivity;
import com.shqcjd.sinopecdemomobile.ui.adapter.EquipmentGroupStandardAdapter;
import com.shqcjd.sinopecdemomobile.ui.base.BaseActivity;
import com.shqcjd.sinopecdemomobile.ui.base.BasePresenter;
import com.shqcjd.sinopecdemomobile.util.UIUtils;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import io.reactivex.disposables.Disposable;

public class EquipmentGroupActivity extends BaseActivity {
    @BindView(R.id.tv_include_title)
    TextView tvIncludeTitle;
    @BindView(R.id.tv_include_finish)
    Button tvIncludeFinish;
    @BindView(R.id.rv_equipment_standard)
    RecyclerView rvEquipmentStandard;
    @BindView(R.id.tv_equipment_group_last)
    TextView tvEquipmentGroupLast;
    @BindView(R.id.btn_equipment_group_guidance)
    Button btnEquipmentGroupGuidance;
    @BindView(R.id.tv_equipment_group_next)
    TextView tvEquipmentGroupNext;
    @BindView(R.id.rl_isnull)
    RelativeLayout rlIsnull;


    private EquipmentGroupActivity context;
    private int tId;
    private String kks;
    private String lastKks = "";
    private String nextKks = "";
    private int epId;
    public final int END_CODE = 12312;

    public List<RadioGroup> radioGroupList = new ArrayList<>();

    @Override
    protected BasePresenter createPresenter() {
        return null;
    }

    @Override
    protected int provideContentViewId() {
        return R.layout.activity_equipment_group;
    }

    @Override
    public void init() {
        super.init();
        kks = getIntent().getStringExtra("kks");
        tId = getIntent().getIntExtra("tId", 1);
    }

    @Override
    public void initView() {
        super.initView();
        context = this;
        tvIncludeFinish.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });

        btnEquipmentGroupGuidance.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent it = new Intent(context, ProblemFeedbackActivity.class);
                it.putExtra("taskId", tId+"");
                it.putExtra("kks", kks);
                startActivity(it);
            }
        });

        tvEquipmentGroupNext.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if(!nextKks.equals("")){
                    kks = nextKks;
                    isInspectionData(nextKks);
                }else{
                    Toast.makeText(context, "当前已经是最后一个", Toast.LENGTH_SHORT).show();
                }
            }
        });

        tvEquipmentGroupLast.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if(!lastKks.equals("")){
                    kks = lastKks;
                    isInspectionData(lastKks);
                }else{
                    Toast.makeText(context, "当前已经是第一个", Toast.LENGTH_SHORT).show();
                }
            }
        });

        getData();
    }

    /**
     * 判断所有的radiobutton有没有被选中
     * @return
     */
    public boolean isCheckAll(){
        for(int i=0; i<radioGroupList.size(); i++){
            RadioGroup radioGroup = radioGroupList.get(i);
            RadioButton rb1 = (RadioButton)radioGroup.getChildAt(0);
            RadioButton rb2 = (RadioButton)radioGroup.getChildAt(1);
            if(!rb1.isChecked()&&!rb2.isChecked()){
                return false;
            }
        }
        return true;
    }

    private void isInspectionData(String kksStr){
        ApiService.intentEquipmentHttp(kksStr.replace("#", "%23"), tId)
                .compose(RxSchedulersHelper.io_main())
                .subscribe(new RxObserver<ResponseData<IntentEquipmentBean>>() {
                    @Override
                    public void _onSubscribe(Disposable d) {
                        super._onSubscribe(d);
                        showWaitingDialog("正在获取巡检信息");
                    }

                    @Override
                    public void _onNext(ResponseData<IntentEquipmentBean> responseData) {
                        if(responseData.retCode==10000){
                            if(responseData.data.check_gps){
                                MyApp.startLocation();
                                MyApp.setOnLocationCallBack(new MyApp.OnLocationInterface() {
                                    @Override
                                    public void onLocationInterface(AMapLocation aMapLocation) {
                                        hideWaitingDialog();
                                        LatLng desLatLng = UIUtils.getGpsChangeLocation(responseData.data.latitude, responseData.data.longitude, context);
                                        //当前坐标
                                        double cLongitude = aMapLocation.getLongitude();
                                        double cLatitude = aMapLocation.getLatitude();
                                        float distance = AMapUtils.calculateLineDistance(desLatLng, new LatLng(cLatitude, cLongitude));
                                        if(distance<1000){
                                            if(responseData.data.isgroup){
                                                Intent it = new Intent(context, EquipmentGroupActivity.class);
                                                it.putExtra("kks", kksStr);
                                                it.putExtra("tId", tId);
                                                startActivity(it);
                                            }else{
                                                Intent it = new Intent(context, EquipmentInspectionActivity.class);
                                                it.putExtra("tId", tId);
                                                it.putExtra("kks", kksStr);
                                                startActivity(it);
                                            }
                                            finish();
                                        }else{
                                            Toast.makeText(context, "当前位置距离巡检点超过了1000米，请靠近一点再试试", Toast.LENGTH_SHORT).show();
                                        }
                                    }
                                });
                            }else{
                                if(responseData.data.isgroup){
                                    Intent it = new Intent(context, EquipmentGroupActivity.class);
                                    it.putExtra("kks", kksStr);
                                    it.putExtra("tId", tId);
                                    startActivity(it);
                                }else{
                                    Intent it = new Intent(context, EquipmentInspectionActivity.class);
                                    it.putExtra("tId", tId);
                                    it.putExtra("kks", kksStr);
                                    startActivity(it);
                                }
                                finish();
                            }
                        }else{
                            Toast.makeText(context, responseData.retMsg, Toast.LENGTH_SHORT).show();
                        }
                    }

                    @Override
                    public void _onError(String errorMessage) {
                        Log.e("tou", errorMessage);
                        hideWaitingDialog();
                        Toast.makeText(context, "任务不存在", Toast.LENGTH_SHORT).show();
                    }

                    @Override
                    public void onComplete() {
                        super.onComplete();
                    }
                });
    }

    private void getData() {
        radioGroupList.clear();
        ApiService.equipmentGroupHttp(tId, kks.replace("#", "%23"))
                .compose(RxSchedulersHelper.io_main())
                .subscribe(new RxObserver<ResponseData<EquipmentGroupBean>>() {
                    @Override
                    public void _onSubscribe(Disposable d) {
                        super._onSubscribe(d);
                        showWaitingDialog("正在加载...");
                    }

                    @Override
                    public void _onNext(ResponseData<EquipmentGroupBean> responseData) {
                        if(responseData.retCode!=10000){
                            Toast.makeText(context, responseData.retMsg, Toast.LENGTH_SHORT).show();
                            return;
                        }
                        tvIncludeTitle.setText(responseData.data.equipment_name);
                        nextKks = responseData.data.next.kks;
                        lastKks = responseData.data.prev.kks;
                        epId = responseData.data.equipment_id;
                        if(responseData.data.prev.name.equals("")){
                            tvEquipmentGroupLast.setText("当前已经是第一个");
                        }else{
                            tvEquipmentGroupLast.setText("上一个/ "+responseData.data.prev.name);
                        }
                        if(responseData.data.next.name.equals("")){
                            tvEquipmentGroupNext.setText("当前已经是最后一个");
                        }else{
                            tvEquipmentGroupNext.setText("下一个/ "+responseData.data.next.name);
                        }

                        rvEquipmentStandard.setLayoutManager(new LinearLayoutManager(context));
                        if(responseData.data.equipment_standard.size()!=0){
                            responseData.data.equipment_standard.add(new EquipmentGroupBean.EquipmentStandardBean());
                            rlIsnull.setVisibility(View.INVISIBLE);
                        }else{
                            rlIsnull.setVisibility(View.VISIBLE);
                        }
                        EquipmentGroupStandardAdapter equipmentGroupStandardAdapter = new EquipmentGroupStandardAdapter(responseData.data.equipment_standard, responseData.data.equipment_check_list, context, epId, tId);
                        rvEquipmentStandard.setAdapter(equipmentGroupStandardAdapter);
                    }

                    @Override
                    public void _onError(String errorMessage) {
                        Log.e("tou", errorMessage);
                        hideWaitingDialog();
                    }

                    @Override
                    public void onComplete() {
                        super.onComplete();
                        hideWaitingDialog();
                    }

                });
    }


    /**
     * 巡检设备组中设备标为正常
     */
    public void updateTrue(int mEid){
        ApiService.getGroupTrue(tId, mEid)
                .compose(RxSchedulersHelper.io_main())
                .subscribe(new RxObserver<ResponseData>() {
                    @Override
                    public void _onSubscribe(Disposable d) {
                        super._onSubscribe(d);
                        showWaitingDialog("正在加载...");
                    }

                    @Override
                    public void _onNext(ResponseData responseData) {
                        if(responseData.retCode!=10000){
                            Toast.makeText(context, responseData.retMsg, Toast.LENGTH_SHORT).show();
                        }
                        nextInspect();
                    }

                    @Override
                    public void _onError(String errorMessage) {
                        Log.e("tou", errorMessage);
                        hideWaitingDialog();
                    }

                    @Override
                    public void onComplete() {
                        super.onComplete();
                        hideWaitingDialog();
                    }
                });
    }

    private void nextInspect(){
        if (isCheckAll()) {
            if (!nextKks.equals("")) {
                isInspectionData(nextKks);
            } else {
                finish();
                Toast.makeText(context, "所有设备巡检完毕", Toast.LENGTH_SHORT).show();
            }
        }
    }

    public void openOrCloseSwitchHttp(String mKks) {
        ApiService.openOrCloseSwitchHttp(mKks.replace("#", "%23"))
                .compose(RxSchedulersHelper.io_main())
                .subscribe(new RxObserver<ResponseData>() {
                    @Override
                    public void _onSubscribe(Disposable d) {
                        super._onSubscribe(d);
                        showWaitingDialog("正在加载...");
                    }

                    @Override
                    public void _onNext(ResponseData responseData) {
                        if (responseData.retCode != 10000) {
                            Toast.makeText(context, responseData.retMsg, Toast.LENGTH_SHORT).show();
                        }
                    }

                    @Override
                    public void _onError(String errorMessage) {
                        Log.e("tou", errorMessage);
                        hideWaitingDialog();
                    }

                    @Override
                    public void onComplete() {
                        super.onComplete();
                        hideWaitingDialog();
                    }
                });
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if(requestCode==END_CODE){
            nextInspect();
        }
    }

}
